<template>
  <div class="share-container">
    <div class="share-content" v-loading="loading">
      <!-- 密码输入对话框 -->
      <el-dialog
        v-model="showPasswordDialog"
        title="输入访问密码"
        width="400px"
        :close-on-click-modal="false"
        :close-on-press-escape="false"
      >
        <el-form @submit.prevent="handlePasswordSubmit">
          <el-form-item label="密码">
            <el-input
              v-model="password"
              type="password"
              placeholder="请输入分享密码"
              @keyup.enter="handlePasswordSubmit"
              autofocus
            />
          </el-form-item>
        </el-form>
        <template #footer>
          <el-button @click="router.back()">取消</el-button>
          <el-button type="primary" @click="handlePasswordSubmit">确定</el-button>
        </template>
      </el-dialog>

      <!-- 文件信息 -->
      <div v-if="file && share && !showPasswordDialog" class="share-info">
        <h2>{{ file.title }}</h2>
        <p v-if="file.description" class="file-description">{{ file.description }}</p>
        <div class="file-meta">
          <span>大小: {{ formatFileSize(file.file_size) }}</span>
          <span>格式: {{ file.format.toUpperCase() }}</span>
          <span v-if="share.expires_at">过期时间: {{ formatDate(share.expires_at) }}</span>
        </div>
        <div class="share-actions">
          <el-button type="primary" @click="handlePreview">预览</el-button>
          <el-button type="primary" @click="handleDownload" v-if="share.allow_download">下载</el-button>
        </div>
      </div>
      <el-result 
        v-else-if="!showPasswordDialog" 
        icon="error" 
        title="分享链接无效" 
        sub-title="该分享链接不存在或已失效" 
      />
    </div>

    <!-- 文件预览对话框 -->
    <KnowledgeFilePreview
      v-model="previewDialogVisible"
      :file-id="previewFileId"
      :file="file || undefined"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { 
  getKnowledgeFileByShareToken, 
  downloadKnowledgeFileByShareToken,
  getKnowledgeFilePreview,
  type KnowledgeFile, 
  type KnowledgeShare 
} from '@/api/knowledge'
import { ResponseParser } from '@/utils/responseParser'
import KnowledgeFilePreview from '@/components/knowledge/KnowledgeFilePreview.vue'

const route = useRoute()
const router = useRouter()
const loading = ref(false)
const file = ref<KnowledgeFile | null>(null)
const share = ref<KnowledgeShare | null>(null)
const password = ref('')
const showPasswordDialog = ref(false)
const previewDialogVisible = ref(false)
const previewFileId = ref<string | undefined>()

// 获取分享文件
const fetchShareFile = async () => {
  try {
    loading.value = true
    const token = route.params.token as string
    const response = await getKnowledgeFileByShareToken(token, password.value || undefined)
    const parsed = ResponseParser.parseResponse<{ file: KnowledgeFile; share: KnowledgeShare }>(response)
    if (parsed.success && parsed.data) {
      file.value = parsed.data.file
      share.value = parsed.data.share
      showPasswordDialog.value = false
    }
  } catch (error: any) {
    console.error('获取分享文件失败:', error)
    if (error?.response?.status === 401) {
      // 需要密码
      showPasswordDialog.value = true
      ElMessage.warning('此分享链接需要密码')
    } else if (error?.response?.status === 410) {
      ElMessage.error('分享链接已过期或访问次数已达上限')
    } else {
      ElMessage.error(error?.response?.data?.message || '获取分享文件失败')
    }
  } finally {
    loading.value = false
  }
}

// 提交密码
const handlePasswordSubmit = () => {
  if (!password.value) {
    ElMessage.warning('请输入密码')
    return
  }
  fetchShareFile()
}

// 预览文件
const handlePreview = async () => {
  if (!file.value) return
  
  try {
    // 使用预览组件
    previewFileId.value = file.value.id
    previewDialogVisible.value = true
  } catch (error: any) {
    console.error('预览文件失败:', error)
    ElMessage.error('预览文件失败')
  }
}

// 下载文件
const handleDownload = async () => {
  if (!file.value || !share.value) return
  
  try {
    const token = route.params.token as string
    const response = await downloadKnowledgeFileByShareToken(token, password.value || undefined)
    const blob = new Blob([response.data])
    const url = window.URL.createObjectURL(blob)
    const link = document.createElement('a')
    link.href = url
    link.download = file.value.filename
    link.click()
    window.URL.revokeObjectURL(url)
    ElMessage.success('下载成功')
  } catch (error: any) {
    console.error('下载失败:', error)
    if (error?.response?.status === 401) {
      ElMessage.warning('此分享链接需要密码')
      showPasswordDialog.value = true
    } else if (error?.response?.status === 403) {
      ElMessage.error('此分享链接不允许下载')
    } else {
      ElMessage.error(error?.response?.data?.message || '下载失败')
    }
  }
}

// 格式化文件大小
const formatFileSize = (bytes: number) => {
  if (bytes === 0) return '0 B'
  const k = 1024
  const sizes = ['B', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return Math.round(bytes / Math.pow(k, i) * 100) / 100 + ' ' + sizes[i]
}

// 格式化日期
const formatDate = (dateStr: string) => {
  if (!dateStr) return '-'
  const date = new Date(dateStr)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

onMounted(() => {
  fetchShareFile()
})
</script>

<style scoped lang="scss">
.share-container {
  min-height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #f5f7fa;
  padding: 40px;
}

.share-content {
  background: white;
  border-radius: 12px;
  padding: 40px;
  max-width: 600px;
  width: 100%;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.share-info {
  h2 {
    margin: 0 0 16px 0;
    font-size: 24px;
    color: #303133;
  }
  
  .file-description {
    margin: 0 0 20px 0;
    color: #606266;
    line-height: 1.6;
  }
}

.file-meta {
  display: flex;
  gap: 20px;
  margin-bottom: 24px;
  color: #909399;
  font-size: 14px;
}

.share-actions {
  display: flex;
  gap: 12px;
}
</style>

